package com.glodon.paas.consumer.service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.text.DateFormat;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.exception.OAuthException;
import oauth.signpost.exception.OAuthNotAuthorizedException;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.glodon.paas.document.api.bean.File;
import com.glodon.paas.sdk.PaasClient;
import com.glodon.paas.sdk.account.Account;
import com.glodon.paas.sdk.document.Document;

/**
 * @author: Don Li
 */
public class SDKCallbackServlet extends HttpServlet {

    @Value("${api.host}")
    private String apiHost;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        Writer writer = resp.getWriter();

        String requestToken = req.getParameter("oauth_token");
        if (requestToken == null || "".equals(requestToken)) {
            writer.write("authorization is denied");
            return;
        }

        try {
            OAuthProvider provider = (OAuthProvider) req.getSession().getAttribute("provider");
            OAuthConsumer consumer = (OAuthConsumer) req.getSession().getAttribute("consumer");

            try {
                // retrieve access token
                provider.retrieveAccessToken(consumer, null);
                writer.write("<b> PAAS API test <br>");
                writer.write("<form method=\"GET\" action=\"sdkTest\" >");
                writer.write("<input type=\"text\" value=\"\" />");
                writer.write("<input value=\"submit\" type=\"submit\"/>");
                writer.write("</form>");
                // persist the access token and secret to consumer's local storage for future usage
            } catch (OAuthNotAuthorizedException e) {
                // not authorized
                writer.write("Your reqeuest is denied.");
                return;
            } catch (OAuthException e) {
                throw new ServletException("Fail to retrieve access token", e);
            }

            PaasClient client = new PaasClient(consumer.getConsumerKey(), consumer.getConsumerSecret(), apiHost);
            client.setTokenWithSecret(consumer.getToken(), consumer.getTokenSecret());

            Account account = client.account();

            writer.write("<br><b>GET user information:</b> <br>");
            writer.write(account.getUserInfoAsJson() + "<br>");
            writer.write(account.getUserInfo().getEmail() + "<br>");
            
            Document document = client.document();
            writer.write("<br>"+document.rootSharedFileByMeAsJson()+" <br>");
            writer.write("<br><b>Create Folder</b> <br>");
            String folderName = DateFormat.getDateTimeInstance().format(new Date());
            File folder = document.createFolder(folderName.replaceAll(":", "-"), "");
            writer.write(folder.getName() + " is created successfully <br>");

            writer.write("<br><b>Metadata of new created Folder</b><br>");
            writer.write(document.getFileAsJson(folder.getId()) + "<br>");

            writer.write("<br><b>Create File Under the Folder</b> <br>");
            byte[] bytes = "Data of Sample File".getBytes();
            InputStream data = new ByteArrayInputStream(bytes);
            File file = document.createFile("SampleFile.txt", folder.getId(), data, bytes.length,false);
            writer.write(file.getName() + " is created successfully <br>");
           
            writer.write("<br><b>Metadata of new created File</b> <br>");
            writer.write(document.getFileAsJson(file.getId()) + "<br>");

            writer.write("<br><b>Data of new created File</b></br>");
            writer.write(IOUtils.toString(document.getFileStream(file.getId())) + "<br>");

            writer.write("<br><b>Get sub-files of a folder</b> <br>");
            writer.write(document.getSubFiles(folder.getId()).length + " sub files are fond <br>");
            writer.write(document.getSubFilesAsJson(folder.getId()) + "<br>");

            writer.write("<br><b>GET root files</b> <br>");
            writer.write(document.getRootFiles().length + " root files are found <br>");
            writer.write(document.getRootFilesAsJson() + "<br>");
            
            writer.write("<br><b>delete created folder to Recycler</b> <br>");
            writer.write(document.delFileToRecycler(folder.getId()) + " <br>");
            
            writer.write("<br><b>delete created file, not in Recycler </b> <br>");
            writer.write(document.delete(file.getId()) + " <br>");
            
            writer.write("<br><b>Clean Recycler </b> <br>");
            writer.write(document.cleanRecycler() + "<br>");
            
//            writer.write("<br><b>Create File By Parts Under the Root Folder</b> <br>");
//            java.io.File f = new java.io.File("C:\\Users\\Public\\Videos\\Sample Videos\\test.wmv");
//            InputStream is = new FileInputStream(f);
//            File file = document.createFile("SampleFile.wmv", "", is, f.length(),true);
//            writer.write(file.getName() + " is created successfully <br>");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }
}
